package com.iretailer.quartz.alarmMail;

import com.alibaba.fastjson.JSON;;
import com.iretailer.model.SiteItem;
import com.iretailer.quartz.common.Task;
import com.iretailer.quartz.common.TaskService;
import com.iretailer.service.ItemService;
import com.iretailer.util.JavaMailWithAttachment;
import com.iretailer.util.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class AlarmMail {

    private Logger log = LoggerFactory.getLogger(AlarmMail.class);
    @Autowired
    private TaskService taskService;
    @Autowired
    private ItemService itemService;

    public void run() {
        log.info("===进入==== 断线日志 === alarmMail");
        Task task = taskService.selectBySpringId("alarmMail");

        //            {"addrLists":[{"recipients":["jiawei.xv@lianbai.com"],"storeId":"all"}],
//            "sendMail": "true","mailHost":"mail.lianbai.com","password":"123345","smtpPort":"465","socketClass":"javax.net.ssl.SSLSocketFactory","socketFallback":"false","username":"service@lianbai.com"}
        String message = task.getOtherMessage();
        AlarmMailModel alarmMailModel = JSON.parseObject(message, AlarmMailModel.class);
        if (alarmMailModel.getOnlineTime() == null && alarmMailModel.getOnlineTime() == 0) {
            alarmMailModel.setOnlineTime(60);
        }
        List<AddrList> addrLists = alarmMailModel.getAddrLists();


        //所有物品
        List<SiteItem> siteItems = itemService.selectAllSiteItem(1);
        List<SiteItem> out_line = new ArrayList<>();
        if (siteItems != null && siteItems.size() > 0) {
            siteItems.forEach((it) -> {
                if (it.getStatus() > alarmMailModel.getOnlineTime()) {
                    out_line.add(it);
                }
            });
        }

        for (AddrList addrList : addrLists) {
            List<SiteItem> sendSiteItems = new ArrayList<>();
            List<String> siteIds = addrList.getSiteIds();
            //如果有all则全部store报警
            if ("all".equalsIgnoreCase(siteIds.get(0))) {
                sendSiteItems.addAll(out_line);
            } else {
                Map<String, List<SiteItem>> out_lineMap = out_line.stream().collect(Collectors.groupingBy(SiteItem::getSiteId));
                siteIds.forEach((it) -> {
                    List<SiteItem> sis = out_lineMap.get(it);
                    if (sis != null) {
                        sendSiteItems.addAll(sis);
                    }
                });
            }
            if (alarmMailModel.getSendMail().equals("true")) {
                StringBuffer html = new StringBuffer("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"/> " +
                        "<title>物品异常报警(" + TimeUtil.localDate2Str(LocalDate.now()) + ")</title>" +
                        "</head><body>");
                html.append("<table border=\"1\" cellspacing=\"0\"cellpadding=\"5\">" +
                        "    <caption>物品异常报警(" + TimeUtil.localDate2Str(LocalDate.now()) + ")</caption>" +
                        "    <tr bgcolor=\"#add8e6\">" +
                        "        <td colspan=\"5\">物品异常信息</td>" +
                        "    </tr>" +
                        "    <tr >" + //bgcolor="#add8e6"
                        "        <th>案场</th>" +
                        "        <th>物品</th>" +
                        "        <th>最后更新时间</th>" +
                        "    </tr>");
                for (int i = 0; i < sendSiteItems.size(); i++) {
                    SiteItem siteItem = sendSiteItems.get(i);
                    if (i % 2 == 0) {
                        html.append("<tr bgcolor=\"#BCD5EC\">");
                    } else {
                        html.append("<tr>");
                    }
                    html.append("<td>" + siteItem.getSiteName() + "</td>" +
                            "<td>" + siteItem.getItemName() + "</td>" +
                            "<td>" + siteItem.getUpdateTime() + "</td>" +
                            "</tr>");
                }
                html.append("</table></body></html>");

                //发送报警邮件
                MaillMessage mm = new MaillMessage(alarmMailModel.getMailHost(), alarmMailModel.getUsername(), alarmMailModel.getPassword(), alarmMailModel.getSmtpPort(), alarmMailModel.getSocketClass(), alarmMailModel.getSocketFallback());
                JavaMailWithAttachment mail = new JavaMailWithAttachment(false, mm);

                if (mm.getPassword() == null || mm.getPassword().trim().length() < 0) {
                    try {
                        mail.doSendEmail("物品异常报警", html.toString(), addrList.getRecipients(), null, null);
                        log.error("发送报警邮件");
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        mail.doSendEmail("物品异常报警", html.toString(), addrList.getRecipients(), null, null, null);
                        log.error("发送报警邮件");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }


    }
}
